<?php
namespace App\Domain\Appfc114;


use App\Model\Appfc114\Project as ModelProject;
use App\Model\Appfc114\ProjectBuild as ModelProjectBuild;
use App\Model\Appfc114\ProjectDynamic as ModelProjectDynamic;
use App\Model\Appfc114\ProjectPic as ModelProjectPic;
use App\Model\Appfc114\ProjectMode as ModelProjectMode;
use Illuminate\Database\Capsule\Manager as DB;


class Project  {

    protected $query;
    protected $metaData;

    public $province_code;//省编码
    public $city_code;//城市编码
    public $pm_level_option;
    public $borough_option;//行政区
    public $circle_option;//环线
    public $direction_option;//方位
    public $region_option;//片区
    public $business_region_option;//商圈
    public $build_year_option;//建筑年代
    public $pic_option;// 图片类型
    public $toward_option; //房屋朝向
    public $fitment_type_option; //内部装修
    public $build_plan_option;//工程进度
    public $build_struct_option;//建筑结构
    public $build_shape_option; //建筑形态
    public $build_type_option;  //建筑类型
    public $attribute_option;   //项目属性
    public $level_option;       //项目定位
    public $status_option;       //项目销售状态
    public $tube_option;        //地铁
    public $view_liv_option;    //小区景观
    public $build_suffix_option;    //楼栋后缀
    public $project_type_option;    //楼栋后缀

    function __construct() {
        $this->query = new QueryCommon();
        $this->metaData = new MetaData();
        $this->pm_level_option = $this->metaData->getPairBaseCodeByType(223);//物业等级
        $this->borough_option = $this->metaData->getPairBaseCodeByType(510100);//区域列表
        $this->circle_option = $this->metaData->getPairBaseCodeByType(211);//获取环线
        $this->direction_option = $this->metaData->getPairBaseCodeByType(205);//获取方位
        $this->build_year_option      = $this->metaData->getPairBaseCodeByType(229);
        $this->pic_option             = $this->metaData->getPairBaseCodeByType(209);
        $this->toward_option          = $this->metaData->getPairBaseCodeByType(215);
        $this->fitment_type_option    = $this->metaData->getPairBaseCodeByType(219);
        $this->build_plan_option      = $this->metaData->getPairBaseCodeByType(230);
        $this->build_struct_option    = $this->metaData->getPairBaseCodeByType(201);
        $this->build_shape_option     = $this->metaData->getPairBaseCodeByType(234);
        $this->build_type_option      = $this->metaData->getPairBaseCodeByType(235);
        $this->attribute_option       = $this->metaData->getPairBaseCodeByType(236);
        $this->level_option           = $this->metaData->getPairBaseCodeByType(237);
        $this->status_option          = $this->metaData->getPairBaseCodeByType(222);
        $this->tube_option            = $this->metaData->getPairBaseCodeByType(238);
        $this->view_liv_option        = $this->metaData->getPairBaseCodeByType(239);
        $this->build_suffix_option    = $this->metaData->getPairBaseCodeByType(240);

        $this->project_type_option = \PhalApi\DI()->config->get('basecode.project_type_option');
        $this->pm_type_option = \PhalApi\DI()->config->get('basecode.pm_type_option');
    }

    public function getlist(){
        $params = \PhalApi\DI()->request->getAll();
        $model = new ModelProject();

        $where = [];
        $whereRaw = " flag = 1 ";
        $order = isset($params['order'])?$params['order']:" id desc ";

        if(isset($params['keywords']) && $params['keywords']!='')//关键字查询
            $whereRaw.= " and (name like '%{$params['keywords']}%' or address = '{$params['keywords']}')";

        $params['pm_type'] = isset($params['pm_type'])?$params['pm_type']:'20301';
        $whereRaw .= " and `pm_type` like '%".$params['pm_type']."%'";

        if(isset($params['city_code']))
            $where["city_code"] = $params['city_code'];
        if(isset($params['digest']) && $params['digest']!='' && $params['digest']!='undefined')
            $where["digest"] = $params['digest'];
        if(isset($params['borough']) && $params['borough']!='')
            $where["borough"] = $params['borough'];
        if(isset($params['project_type']) && $params['project_type']!='')
            $where["project_type"]=$params['project_type'];
        if(isset($params['project_type']) && $params['project_type']!='')
            $where["project_type"]= $params['project_type'];
        if(isset($params['is_boss']) && $params['is_boss']!='' && $params['is_boss']!='undefined')
            $where["is_boss"]= $params['is_boss'];
        if(isset($params['is_poster']) && $params['is_poster']!='')
            $where["is_poster"]= $params['is_poster'];
        //DB::connection()->enableQueryLog();
        $page = isset($params["page"])?$params["page"]:1;
        $pageSize = isset($params["pageSize"])?$params["pageSize"]:30;
        $limitdata = $this->query->getPaginationDC($page,$pageSize);
        $items = $model->getListItems($where,$whereRaw, $limitdata, $order);
        //print_r(DB::getQueryLog());exit;
        foreach ($items as $key=>$item){
            $items[$key]['project_type_val'] =$this->pm_type_option[$item['project_type']];
            $items[$key]['borough_val'] = $this->borough_option[$item['borough']];
            $items[$key]['build_year_val'] = $this->build_year_option[$item['build_year']];
            //处理物业
            $_pm_type = explode(',',$item['pm_type']);
            $pm_type = '';
            foreach($_pm_type as $k=>$v){
                $items[$key]['pm_type_val'] .= $this->pm_type_option[$v].',';
                if($pm_type=='')$pm_type=$v;
            }
            $items[$key]['pm_type_val'] = substr($items[$key]['pm_type_val'],0,-1);
            $items[$key]['pm_info'] = $this->projectPmInfo($pm_type,$item['id']);//住宅信息

            //处理图片
            $items[$key]['img_url'] = str_replace('.','_s.',$item['img_url']);

            if($item['is_boss']==1) {
                $items[$key]['is_boss_val'] = '分销';
                $items[$key]['is_boss_imgurl'] = 'fenxiao.png';
            }
            if($item['digest']==24401) {
                $items[$key]['digest_val'] = '热门';
                $items[$key]['digest_imgurl'] = 'hot.png';
            }
        }

        return $items;
    }

    public function detail($project_id){
        $model = new ModelProject();
        $Info = $model->where("id",$project_id)->first();
        $Info['pm_type'] = explode(",", $Info['pm_type']);
        $Info['borough_val'] = $this->borough_option[$Info['borough']];
        $Info['direction_val'] = $this->direction_option[$Info['direction']];
        $Info['circle_val'] = $this->circle_option[$Info['circle']];
        $Info['total_occupy'] = $Info['total_occupy'].'平方米';
        $Info['total_area'] = $Info['total_area'].'平方米';

        //根据物业类型,获取对应信息[todo:目前默认获取住宅信息]
        $Info['pm_info'] = array();
        foreach($Info['pm_type'] as $key=>$val){
            $Info['pm_type_val'] .= $this->tranPmType($val,$this->pm_type_option,3);
            if($val=='20301' && count($Info['pm_info'])==0)
                $Info['pm_info'] = $this->projectPmInfo($val,$Info['id']);//住宅信息

            if($val=='20306' && count($Info['pm_info'])==0)
                $Info['pm_info'] = $this->projectPmInfo($val,$Info['id']);//商业信息

        }

        if($Info['is_boss']==1)
            $Info['is_boss_val'] = '分销';
        if($Info['digest']==1)
            $Info['digest_val'] = '热门';

        //预售信息
        $Info['sell'] = array('all_num'=>'239','poor_num'=>'115','must_num'=>'85','pub_num'=>'39');

        //楼盘图片
        $allpics= $this->projectPic();
        $Info['allpics'] = $allpics;//所有图片
        $huxingpics = array();//户型图
        $pics = array();//除户型图以外的所有图片
        foreach ($allpics as $key=>$item){
            if($item->code=='20901'){
                $huxingpics[] = $item;
            }else{
                $pics[] = $item;
            }
        }
        $Info['huxingpics'] = $huxingpics;
        $Info['pics'] = $pics;

        //获取项目动态
        $Info['dynamic'] = $this->projectDynamic();

        //更新项目浏览次数
        $this->updateHitsNum($project_id);

        //获取置业顾问
        $Info['seller'] = array(
            array('name'=>'李青青','mobile'=>'18980830015','wechat'=>'','imgurl'=>'../../../images/avtor.png','job'=>''),
            array('name'=>'曾露露','mobile'=>'18980830015','wechat'=>'','imgurl'=>'../../../images/avtor.png','job'=>''),
            array('name'=>'黎小黎','mobile'=>'18980830015','wechat'=>'','imgurl'=>'../../../images/avtor.png','job'=>''),
        );

        return $Info;
    }

    public function build()
    {
        $params = \PhalApi\DI()->request->getAll();
        $model = new ModelProjectBuild();
        $data = $model->where("project_id",$params["project_id"])->get();
        return $data;
    }

    public function projectMode()
    {
        $params = \PhalApi\DI()->request->getAll();
        $model = new ModelProjectMode();
        $data = $model->where("project_id",$params["project_id"])->get();
        return $data;
    }

    public function projectDynamic()
    {
        $params = \PhalApi\DI()->request->getAll();
        $model = new ModelProjectDynamic();

        $where = [];
        $whereRaw = " 1 = 1 ";
        $order = isset($params['order'])?$params['order']:" id desc ";
        $where["flag"]= isset($params['flag'])?$params['flag']:1;
        if(isset($params['project_id']))
            $where["project_id"] = $params['project_id'];
        $page = isset($params["page"])?$params["page"]:1;
        $pageSize = isset($params["pageSize"])?$params["pageSize"]:10;
        $limitdata = $this->query->getPaginationDC($page,$pageSize);
        $data = $model->getListItems($where,$whereRaw, $limitdata, $order);
        //$data = $model->where("project_id",$params["project_id"])->get();
        foreach ($data as $key=>$item){
            $data[$key]["start_date_val"] = date("Y-m-d",$item["start_date"]);
        }
        return $data;
    }

    public function projectPic($code='all')
    {
        $params = \PhalApi\DI()->request->getAll();
        $model = new ModelProjectPic;
        //DB::connection()->enableQueryLog();
        $where = ' fc_project_pic.flag=1';
        if($code!='all'){
            $where = ' and fc_project_pic.code='.$code;
        }
        $data = $model->where("project_id",$params["project_id"])
            ->whereRaw($where)
            ->leftJoin("fc_project_attach as a","a.id","=","fc_project_pic.attach_id")
            ->get(["fc_project_pic.*","a.name as attach_name","a.url as attach_url"]);
        foreach ($data as $key=>$img){
            $data[$key]['attach_url_m'] = str_replace('.','_m.',$img['attach_url']);
            $data[$key]['attach_url_s'] = str_replace('.','_s.',$img['attach_url']);
        }
       //print_r(DB::getQueryLog());exit;
        return $data;
    }

    /* 物业类型转换 */
    public function tranPmType($pm_type,$pm_type_option,$style=3){
        $pm_type = explode(",", $pm_type);
        $pm_type_val = '';
        foreach ($pm_type as $val){
            switch ($val){
                case '20301'://住宅
                    if($style==1)
                        $pm_type_val .='<span class="tag tag_green fang-tag">'.$pm_type_option[$val].'</span>';
                    elseif($style==2)
                        $pm_type_val .='<span class="badge badge-success mls">'.$pm_type_option[$val].'</span>';
                    else
                        $pm_type_val .= $pm_type_option[$val].',';
                    break;
                case '20302'://公寓
                    if($style==1)
                        $pm_type_val .='<span class="tag tag_yellow fang-tag">'.$pm_type_option[$val].'</span>';
                    elseif($style==2)
                        $pm_type_val .='<span class="badge badge-success mls">'.$pm_type_option[$val].'</span>';
                    else
                        $pm_type_val .= $pm_type_option[$val].',';
                    break;
                case '20303'://别墅
                    if($style==1)
                        $pm_type_val .='<span class="tag tag_darkorange fang-tag">'.$pm_type_option[$val].'</span>';
                    elseif($style==2)
                        $pm_type_val .='<span class="badge badge-success mls">'.$pm_type_option[$val].'</span>';
                    else
                        $pm_type_val .= $pm_type_option[$val].',';
                    break;
                case '20306'://写字楼
                    if($style==1)
                        $pm_type_val .='<span class="tag tag_darkorange fang-tag">'.$pm_type_option[$val].'</span>';
                    elseif($style==2)
                        $pm_type_val .='<span class="badge badge-success mls">'.$pm_type_option[$val].'</span>';
                    else
                        $pm_type_val .= $pm_type_option[$val].',';
                    break;
                default:
                    if($style==1)
                        $pm_type_val .='<span class="tag tag_softblue fang-tag">'.$pm_type_option[$val].'</span>';
                    elseif($style==2)
                        $pm_type_val .='<span class="badge badge-success mls">'.$pm_type_option[$val].'</span>';
                    else
                        $pm_type_val .= $pm_type_option[$val].',';
                    break;
            }
        }
        return $pm_type_val;
    }

    /* 户型转换 */
    public function tranHuxing($ting='',$shi='',$type=1){
        $shiStr = '';
        $tingStr = '';
        switch($shi){
            case '1':
                $shiStr ='一室';
                break;
            case '2':
                $shiStr ='二室';
                break;
            case '3':
                $shiStr ='三室';
                break;
            case '4':
                $shiStr ='四室';
                break;
            case '5':
                $shiStr ='五室以上';
                break;
            default:
                $shiStr ='五室以上';
                break;
        }
        switch($ting){
            case '1':
                $tingStr = '一厅';
                break;
            case '2':
                $tingStr = '二厅';
                break;
            case '3':
                $tingStr = '三厅';
                break;
            case '4':
                $tingStr = '四厅';
                break;
            default:
                $tingStr = '四厅以上';
                break;
        }
        $huxing = $shiStr.$tingStr;
        return $huxing;
    }

    /* 根据物业类型返回表名 */
    public function getPmTypeTable($pm_type){
        $result = 'house';
        switch($pm_type){
            case '20303'://别墅
                $result ='villa';
                break;
            case '20308'://商业
                $result ='business';
                break;
            case '20306'://写字楼
                $result ='office';
                break;
            case '20302'://公寓
                $result ='apartment';
                break;
            case '20301'://住宅
                $result ='house';
                break;
            default:
                $result ='house';
                break;
        }

        return $result;
    }

    /* 根据物业类型获取详细信息 */
    public function projectPmInfo($pm_type,$project_id){
        $table = $this->getPmTypeTable($pm_type);
        $sql = "select * from fc_project_".$table." where project_id = :id";
        $pmInfo = DB::select($sql, [':id'=>$project_id]);
        $Info = $pmInfo[0];

        $data['pm_type'] = $pm_type;
        $data['price'] = $Info->price.'万元';
        $data['must_price'] = "50万";//验资金额
        $data['price_average'] = $Info->price_average.'元/m²';//均价
        $data['unit_price'] = $Info->price_min . "-" . $Info->price_max . "元/m²";//单价
        $data['status_val'] = $this->status_option[$Info->status];
        $data['status_color'] = $this->statusColor($Info->status);
        if($Info->price_min==0 || $Info->price_max==0){
            $data['cprice'] = $data['price_average'];
        }else{
            $data['cprice'] = $data['unit_price'];
        }
        $data['open_date_val'] = date('Y-m-d',$Info->open_date);
        $data['huxing_area'] = "约".$Info->area_min . "-" . $Info->area_max . "m²";//主力户型
        $data['fitment_type_val'] = $this->fitment_type_option[$Info->fitment_type];
        $data['use_age'] = isset($Info->use_age)?$Info->use_age.'年':'';
        $data['live_date_val'] = date('Y-m-d',$Info->live_date);
        $data['cubage'] = isset($Info->cubage)?$Info->cubage.'%':'';
        $data['greenbelt'] = isset($Info->greenbelt)?$Info->greenbelt.'%':'';
        $data['parking_num'] = $Info->parking_num.'个';
        $data['floor'] = $Info->floor;
        $data['sell_build'] = 'A区18栋、C区20栋';//销售楼栋
        $data['family_num'] = $Info->family_num;//总户数
        $data['manage_price'] = $Info->manage_price;
        $data['elevator'] = $Info->elevator;
        $data['manage_company'] = $Info->manage_company;
        $data['brok_price'] = !empty($Info->brok_price)?$Info->brok_price:'';

        switch ($pm_type){
            case '20301':
                //$Info['pm_level_val'] = $this->pm_level_option[$Info['pm_level']];
                break;
            default:
                break;
        }
        return $data;
    }

    /* 更新浏览次数 */
    public function updateHitsNum($project_id){
        DB::connection()->enableQueryLog();
        $model = new ModelProject();
        $id = $model->where("id",$project_id)->increment('hits_num');
        //print_r(DB::getQueryLog());exit;
        return $id;
    }

    /* 返回项目销售状态颜色 */
    private function statusColor($status){
        switch ($status){
            case '0':
                $color='gray';
                break;
            case '22201':
                $color='orange';
                break;
            case '22202':
                $color='green';
                break;
            default:
                $color='red';
                break;
        }
        return $color;
    }


}
